# Copyright (c) 2023, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.model.document import Document

class SRMReconciliation(Document):
	# 起始日期检查,不允许重叠
	# def before_save(self):
	# 	ap = frappe.db.get_list('SRM Reconciliation', filters={"supplier_number": self.supplier_number, "date_to": [">=", self.date_from], "name": ["!=", self.name]})
	# 	if len(ap) > 0:
	# 		frappe.throw(_(f'对账日期与{ap[0].name}有冲突'))

	@frappe.whitelist()
	def get_from_history(self):
		# 查找该供应商历史的最新对账单: 以date_to倒序
		last_doc = frappe.db.get_all(self.doctype, fields=['name', 'date_to'], filters={'supplier_number': self.supplier_number, 'name': ['!=', self.name]}, order_by = 'date_to desc', page_length = 1)
		if last_doc:
			return last_doc
		else:
			frappe.msgprint(_('No History Reconciliation Find'))

	@frappe.whitelist()
	def copy_from_history(self, history_name):
		doc = frappe.get_doc(self.doctype, history_name)
		if doc.quarters:
			self.quarters = []
			for i in doc.quarters:
				self.append('quarters', {'months': i.months, 'sales_amount': i.sales_amount, 'amount_collected': i.amount_collected, 'prepayment': i.prepayment, 'deduction': i.deduction, 'ar_c_ap': i.ar_c_ap})
			self.save()
			self.reload()